package com.zerosoft.guotai.handler;

import com.zerosoft.guotai.dao.G6EventPackage;
import com.zerosoft.guotai.dao.G7EventPackage;
import com.zerosoft.guotai.mqtt.MqttSendClient;
//import jakarta.annotation.Resource;
import lombok.*;

//import javax.annotation.Resource;
import java.io.*;
import java.net.Socket;
import java.nio.ByteBuffer;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class SocketHandler implements Runnable{
    /**
     * 客户端socket
     */
    private Socket clientSocket;

//    @Resource
    //线程中不能使用Resource注解
    private MqttSendClient mqttSendClient;

    /**
     * Runs this operation.
     */
    @Override
//    @SneakyThrows
    public void run() {
        System.out.println("客户端连接成功!");
        try(
            // 获取请求数据信息，in/out方式为字符方式交互，默认为UTF-8编码，stream方式为byte数组方式交互
//            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
            DataInputStream dataInputStream = new DataInputStream(clientSocket.getInputStream());
            DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream())
        ){
            System.out.println("接收数据开始处理!");
//            String inputLine;
//            char[] buff = new char[1024];
            byte[] buff = new byte[1024];
            int len;
            while((len = dataInputStream.read(buff)) != -1){
                byte tag =buff[0];
//                String str = new String(buff,0,len);
                byte[] pkg = new byte[len];
                System.arraycopy(buff,0,pkg,0,len);
//                System.out.println("收到数据包: "+GuotaiUtil.convertToHexString(pkg,16));
                // 判断是否为国泰怡安G7设备数据包
                if(Integer.valueOf(tag) == 0x7e)
                {
                    final G7EventPackage g7EventPackage = GuotaiUtil.convertToEventPackage(pkg);
                    if(g7EventPackage.isEventPackage()){
                        String sJson = g7EventPackage.getEventInfo().convertToGuotaiEventParse().parseJson();
                        System.out.println("解析数据成功:"+sJson);
                        //发布消息
                        mqttSendClient.publish(true,"event/guotai",sJson);
                        //回复确认
                        byte[] retmsg = new byte[4];
                        ByteBuffer bb = ByteBuffer.wrap(retmsg);
                        bb.put((byte)0x7e);
                        bb.put((byte)0x04);
                        bb.put((byte)0x01);
                        bb.put(GuotaiUtil.calculateCheckSum(retmsg));
                        System.out.println("回复确认: "+GuotaiUtil.convertToHexString(retmsg,16));
//                        out.println(retmsg);
                        dataOutputStream.write(retmsg);
                        dataOutputStream.flush();
                    }
                    else if(g7EventPackage.isResponsePackage()){
                        //G7心跳包返回
                        System.out.println("G7心跳: "+GuotaiUtil.convertToHexString(pkg,16));
                        dataOutputStream.write(pkg);
                        dataOutputStream.flush();
                    }
                    else{
                        //原包返回
                        System.out.println("非事件包: "+GuotaiUtil.convertToHexString(pkg,16));
                        dataOutputStream.write(pkg);
                        dataOutputStream.flush();
                        //测试发布消息
//                        mqttSendClient.publish(true,"guotai/event",new String(pkg));
//                        out.println(str.toCharArray());
                    }
                }else if(len >= 4 && "$$".equals(new String(buff,0,2))){ //G6设备数据包
                    System.out.println("G6数据包: "+GuotaiUtil.convertToHexString(pkg,16));
                    G6EventPackage g6EventPackage = GuotaiUtil.convertToG6EventPackage(pkg);
                    if(g6EventPackage.isEventPackage()){
                        String sJson = g6EventPackage.getEventParse().parseJson();
                        System.out.println("解析数据成功:"+sJson);
                        //发布消息
                        mqttSendClient.publish(true,"event/guotai",sJson);
                        //回复确认:如果主机模式为BA，则不需要返回，如果是CRT方式，需要返回“$$"
                        byte[] retmsg = new byte[2];
                        ByteBuffer bb = ByteBuffer.wrap(retmsg);
                        bb.put((byte)'$');
                        bb.put((byte)'$');
                        dataOutputStream.write(retmsg);
                        dataOutputStream.flush();
                    }
                    else{
                        //原包返回
                        System.out.println("数据包格式有误: "+GuotaiUtil.convertToHexString(pkg,16));
                        dataOutputStream.write(pkg);
                        dataOutputStream.flush();
                    }
                }
                else{
                    //原包返回
                    System.out.println("非国泰数据包: "+GuotaiUtil.convertToHexString(pkg,16));
//                    byte[] retmsg = new byte[4];
//                    ByteBuffer bb = ByteBuffer.wrap(retmsg);
//                    bb.put((byte)0x7e);
//                    bb.put((byte)0x04);
//                    bb.put((byte)0x01);
//                    System.out.println(String.format("0x%02X-0x%02X-0x%02X-0x%02X",retmsg[0],retmsg[1],retmsg[2],retmsg[3]));
//                    bb.put(GuotaiUtil.calculateCheckSum(retmsg));
//                    System.out.println(String.format("0x%02X-0x%02X-0x%02X-0x%02X",retmsg[0],retmsg[1],retmsg[2],retmsg[3]));
//                    System.out.println("回复确认: "+ GuotaiUtil.convertToHexString(retmsg,16));
//                    System.out.println("数据包长度："+retmsg.length);
////                    out.println(new String(retmsg, StandardCharsets.ISO_8859_1).toCharArray());
////                    out.println(str.toCharArray());
//                    dataOutputStream.write(retmsg);
//                    dataOutputStream.flush();

                    dataOutputStream.write(pkg);
                    dataOutputStream.flush();
                }

            }
//            while((inputLine = in.readLine()) != null){
//
//            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("客户端连接异常:"+e.getMessage());
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                System.out.println("关闭连接失败:"+e.getMessage());
            }
        }

//        // 获取请求数据信息
//        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
//        System.out.println("接收数据开始处理!");
//        System.out.println("客户端连接成功!");


            // 读取数据前6位，获取请求数据长度
//        char[] bodyBytes = new char[6];
//        in.read(bodyBytes);
//        String dataLengthStr = new String(bodyBytes);
//        System.out.println("请求数据长度:" + dataLengthStr);

        // 获取请求数据信息
//        Integer dataLength = Integer.parseInt(dataLengthStr);
//        System.out.println("请求数据长度:" + dataLength);

//        bodyBytes = new char[dataLength];
//        in.read(bodyBytes);
//        String requestBodyInfo = new String(bodyBytes);
//        System.out.println("请求数据:" + requestBodyInfo);

//        // 请求数据转换为Person对象
//        Product product = JSON.parseObject(requestBodyInfo, Product.class);
//        product.setId(IdUtil.simpleUUID());
//        productMapper.insert(product);

        // 响应数据
//        String rspJSONInfo = JSONObject.toJSONString(product);

        // 响应数据长度标识位 eg: 000667
//        String prefixLength = SocketUtil.leftFixedZero(6, rspJSONInfo.length());

        // 最终响应数据
//        String finalRspInfo = prefixLength.concat(rspJSONInfo);
//        System.out.println("响应数据:" + finalRspInfo);
//        out.println("ret:"+dataLengthStr);
    }
}
